﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace DelCompany
{
    public partial class Form1 : Form
    {
        #region

        Thread myThread;

        Int32 Successed = 0;
        Int32 Failed = 0;

        #endregion

        #region Form

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            InitMessage();
        }

        #endregion

        #region Company

        #region Button

        private void btnCheckCompany_Click(object sender, EventArgs e)
        {
            if (!CheckCompanyID()) return;

            if (GlobalAttrib.CompanyID.Split(',').Length > 10)
            {
                MessageBox.Show("商家数量大于10个时不允许使用该功能");
                return;
            }

            string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);          

            string err = "";
            if (!DelCompanyDal.DBO.CheckLogin(conn, out err))
            {
                MessageBox.Show("数据库连接失败," + err);
                return;
            }

            CheckData checkData = new CheckData("Company");
            checkData.ShowDialog();
        }

        private void btnViewCompanyName_Click(object sender, EventArgs e)
        {
            if (!CheckCompanyID()) return;
            if (GlobalAttrib.CompanyID.Split(',').Length > 10)
            {
                MessageBox.Show("商家数量大于10个时不允许使用该功能");
                return;
            }

            string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);          

            string err = "";
            if (!DelCompanyDal.DBO.CheckLogin(conn, out err))
            {
                MessageBox.Show("数据库连接失败," + err);
                return;
            }
            
            string sql = File.ReadAllText(GlobalAttrib.CompanyCheckFile).Replace("{companyID}", GlobalAttrib.CompanyID);
            string CheckResult = "";
            DataTable dt = new DataTable();

            try
            {
                dt = DelCompanyDal.Company.GetCompanyInfo(conn, sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    CheckResult += dt.Rows[i][j].ToString() + " : ";
                }
                CheckResult = CheckResult.Remove(CheckResult.Length - 3) + "\n";
            }
            if (string.IsNullOrEmpty(CheckResult)) CheckResult = "商家不存在";

            MessageBox.Show(CheckResult);
        }

        private void btnDelCompany_Click(object sender, EventArgs e)
        {
            if (!CheckCompanyID()) return;

            if (MessageBox.Show("商家信息删除后将不可恢复，确认删除吗？", "操作确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);          

                string err = "";
                if (!DelCompanyDal.DBO.CheckLogin(conn, out err))
                {
                    MessageBox.Show("数据库连接失败," + err);
                    return;
                }

                this.tabControl1.Enabled = false;
                this.toolStripProgressBar1.Value = 0;
                this.toolStripStatusLabel1.Text = "";
                Successed = 0;
                Failed = 0;
                myThread = new Thread(new ThreadStart(DelCompany));
                myThread.Start();
                GlobalAttrib.IsThread = true;
                this.timer1.Start();
            }
        }

        #endregion

        private bool CheckCompanyID()
        {
            if (string.IsNullOrEmpty(this.rtbCompanyID.Text))
            {
                MessageBox.Show("请输入商家ID");
                return false;
            }

            Regex regex = new Regex(@"^[\d,]+$");
            if (regex.IsMatch(this.rtbCompanyID.Text))
            {
                GlobalAttrib.CompanyID = this.rtbCompanyID.Text;
            }
            else
            {
                MessageBox.Show("商家ID输入格式错误，请检查！");
                return false;
            }

            GlobalAttrib.connUID = this.tbUserID.Text;
            GlobalAttrib.connPASS = this.tbPassWord.Text;
            return true;
        }

        #region Thread

        private void DelCompany()
        {
            string sql = "";
            string[] CompanyIDs = GlobalAttrib.CompanyID.Split(',');
            string fileTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
            GlobalAttrib.UrlLogsFile = @".\Logs\url" + fileTime + ".txt";
            GlobalAttrib.PicLogsFile = @".\Logs\pic" + fileTime + ".txt";

            string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);          
            
            this.toolStripProgressBar1.Maximum = CompanyIDs.Length;

            foreach (string CompanyID in CompanyIDs)
            {
                this.toolStripStatusLabel1.Text = "查询" + CompanyID;
                try
                {
                    sql = File.ReadAllText(GlobalAttrib.CompanySelFile).Replace("{companyID}", CompanyID);

                    if (!DelCompanyDal.Company.WriteCompanyInfo(conn, sql, GlobalAttrib.UrlLogsFile, GlobalAttrib.PicLogsFile))
                    {
                        Failed++;
                        outCompanyError("查询" + CompanyID + "操作失败");
                    }
                    else
                    {
                        this.toolStripStatusLabel1.Text = "删除" + CompanyID;
                        sql = File.ReadAllText(GlobalAttrib.CompanyDelFile).Replace("{companyID}", CompanyID);
                        if (!DelCompanyDal.Company.DelCompany(conn, sql))
                        {
                            Failed++;
                            outCompanyError("删除" + CompanyID + "操作失败");
                        }
                    }
                    Successed++;
                }
                catch (Exception ex)
                {
                    Failed++;
                    outCompanyError(CompanyID + ": " + ex.Message);
                }

                this.toolStripProgressBar1.Value++;
            }

            outCompanyLogFile(GlobalAttrib.CompanyID);

            this.toolStripStatusLabel1.Text = "商家删除已完成。成功：" + Successed + "，失败：" + Failed;
            MessageBox.Show("操作成功，请检查确认！");

            Message msg = new Message();
            msg.ShowDialog();

            GlobalAttrib.IsThread = false;
        }

        private void outCompanyLogFile(string txt)
        {
            FileStream fs = new FileStream(GlobalAttrib.CompanyLogFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            StreamWriter text = new StreamWriter(fs);
            text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + txt);
            text.Close();
            fs.Close();
            fs.Dispose();
        }

        private void outCompanyError(string txt)
        {
            FileStream fs = new FileStream(GlobalAttrib.CompanyErrorFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            StreamWriter text = new StreamWriter(fs);
            text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + txt);
            text.Close();
            fs.Close();
            fs.Dispose();
        }

        #endregion

        #endregion

        #region Message

        private void InitMessage()
        {
            FileInfo[] Files = new DirectoryInfo(GlobalAttrib.MessageSelRoot).GetFiles();
            this.cbbTable.Items.Clear();
            foreach (FileInfo file in Files)
            {
                this.cbbTable.Items.Add(file.Name.Replace(file.Extension, ""));
            }
            if (this.cbbTable.Items.Count > 0) this.cbbTable.SelectedIndex = 0;
        }

        #region Button

        private void btnCheckInfo_Click(object sender, EventArgs e)
        {
            if (!CheckMessageID()) return;

            if (GlobalAttrib.InfoID.Split(',').Length > 10)
            {
                MessageBox.Show("信息数量大于10个时不允许使用该功能");
                return;
            }

            string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);          

            string err = "";
            if (!DelCompanyDal.DBO.CheckLogin(conn, out err))
            {
                MessageBox.Show("数据库连接失败," + err);
                return;
            }

            CheckData checkData = new CheckData("Info");
            checkData.ShowDialog();
        }

        private void btnDelInfo_Click(object sender, EventArgs e)
        {
            if (!CheckMessageID()) return;

            if (MessageBox.Show("商家信息删除后将不可恢复，确认删除吗？", "操作确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);          

                string err = "";
                if (!DelCompanyDal.DBO.CheckLogin(conn,out err))
                {
                    MessageBox.Show("数据库连接失败," + err);
                    return;
                }

                this.tabControl1.Enabled = false;
                this.toolStripProgressBar1.Value = 0;
                this.toolStripStatusLabel1.Text = "";
                Successed = 0;
                Failed = 0;
                myThread = new Thread(new ThreadStart(DelInfo));
                myThread.Start();
                GlobalAttrib.IsThread = true;
                this.timer1.Start();
            }
        }

        #endregion

        private bool CheckMessageID()
        {
            if (string.IsNullOrEmpty(this.rtbInfoID.Text))
            {
                MessageBox.Show("请输入商家ID");
                return false;
            }

            Regex regex = new Regex(@"^[\d,]+$");
            if (regex.IsMatch(this.rtbInfoID.Text))
            {
                GlobalAttrib.InfoID = this.rtbInfoID.Text;
            }
            else
            {
                MessageBox.Show("商家ID输入格式错误，请检查！");
                return false;
            }

            GlobalAttrib.connUID = this.tbUserID.Text;
            GlobalAttrib.connPASS = this.tbPassWord.Text;
            GlobalAttrib.MessageSelFile = GlobalAttrib.MessageSelRoot + (GlobalAttrib.MessageSelRoot.EndsWith(@"\") ? "" : @"\") + this.cbbTable.SelectedItem.ToString() + @".sql";
            GlobalAttrib.MessageDelFile = GlobalAttrib.MessageDelRoot + (GlobalAttrib.MessageDelRoot.EndsWith(@"\") ? "" : @"\") + this.cbbTable.SelectedItem.ToString() + @".sql";
            GlobalAttrib.MessageTable = this.cbbTable.SelectedItem.ToString();
            return true;
        }

        #region Thread

        private void DelInfo()
        {
            string sql = "";
            string[] InfoIDS = GlobalAttrib.InfoID.Split(',');
            string fileTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
            GlobalAttrib.UrlLogsFile = @".\Logs\url" + fileTime + ".txt";
            GlobalAttrib.PicLogsFile = @".\Logs\pic" + fileTime + ".txt";

            string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString.Replace("{uid}", this.tbUserID.Text).Replace("{pass}", this.tbPassWord.Text);
            
            this.toolStripProgressBar1.Maximum = InfoIDS.Length;

            foreach (string InfoID in InfoIDS)
            {
                this.toolStripStatusLabel1.Text = "查询" + InfoID;
                try
                {
                    sql = File.ReadAllText(GlobalAttrib.MessageSelFile).Replace("{InfoID}", InfoID);

                    if (!DelCompanyDal.Message.WriteMessageInfo(conn, sql, GlobalAttrib.UrlLogsFile, GlobalAttrib.PicLogsFile))
                    {
                        Failed++;
                        outMessageError("查询[" + GlobalAttrib.MessageTable + "]" + InfoID + "操作失败");
                    }
                    else
                    {
                        this.toolStripStatusLabel1.Text = "删除" + InfoID;
                        sql = File.ReadAllText(GlobalAttrib.MessageDelFile).Replace("{InfoID}", InfoID);
                        if (!DelCompanyDal.Message.DelMessage(conn, sql))
                        {
                            Failed++;
                            outMessageError("删除[" + GlobalAttrib.MessageTable + "]" + InfoID + "操作失败");
                        }
                    }
                    Successed++;
                }
                catch(Exception ex)
                {
                    Failed++;
                    outMessageError("[" + GlobalAttrib.MessageTable + "]" + InfoID + ": " + ex.Message);
                }

                this.toolStripProgressBar1.Value++;
            }

            outMessageLogFile("[" + GlobalAttrib.MessageTable + "]" + GlobalAttrib.InfoID);

            this.toolStripStatusLabel1.Text = "信息删除已完成。成功：" + Successed + "，失败：" + Failed;
            MessageBox.Show("操作成功，请检查确认！");

            Message msg = new Message();
            msg.ShowDialog();

            GlobalAttrib.IsThread = false;
        }

        private void outMessageLogFile(string txt)
        {
            FileStream fs = new FileStream(GlobalAttrib.MessageLogFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            StreamWriter text = new StreamWriter(fs);
            text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + txt);
            text.Close();
            fs.Close();
            fs.Dispose();
        }

        private void outMessageError(string txt)
        {
            FileStream fs = new FileStream(GlobalAttrib.MessageErrorFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            StreamWriter text = new StreamWriter(fs);
            text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + txt);
            text.Close();
            fs.Close();
            fs.Dispose();
        }

        #endregion

        #endregion

        private void CheckThread()
        {
            if (GlobalAttrib.IsThread == false)
            {
                this.tabControl1.Enabled = true;
                this.timer1.Stop();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            CheckThread();
        }
    }
}
